package spring.cloud.feign.client;

import java.util.concurrent.ThreadLocalRandom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;

//import com.alibaba.csp.sentinel.annotation.SentinelResource;
//import com.alibaba.csp.sentinel.slots.block.BlockException;

import reactor.core.publisher.Mono;

@RestController
public class WebFluxController {
	@Autowired
	private GreetingClient greetingClient;

	@Autowired
    private WebClient.Builder webClientBuilder;
	
	@RequestMapping("/get-greeting")
	public Mono<String> greeting() {
		
		return webClientBuilder.build().get().uri("http://SPRING-CLOUD-EUREKA-CLIENT/greeting").retrieve()
		.bodyToMono(String.class);
	    
	    
 		//return  greetingClient.greeting(); 
	} 
	
	
	@RequestMapping("/get-greeting2")
	public Mono<String> greeting2() {
		
		return  greetingClient.greeting(); 
	} 
	
	@RequestMapping("/execption-rule")
	@SentinelResource(value = "ERROR_RATIO" ,fallback="fallback",
	defaultFallback = "defaultFallback", blockHandler = "handleStringException",
	exceptionsToIgnore = {
			IllegalStateException.class })
	public Mono<String> execptionRule() {
		 if (ThreadLocalRandom.current().nextInt(0, 100) > 55) {
			  if (ThreadLocalRandom.current().nextInt(0, 100) > 55) {
	              // no fallback throw direct
				throw new RuntimeException("oops");
				//  return Mono.error( new RuntimeException("oops")); 
	          }else {
				  return Mono.error( new IllegalStateException("not be catch,throw direct")); 

	          }
	        
	     }
		 
		return Mono.just("no execption and block");
		// model.addAttribute("greeting", greetingClient.greeting());
		// return "greeting-view";
	}

	public Mono<String>   handleStringException(BlockException ex) {
		return Mono.just ("hello from ExceptionUtil, ex= : " + ex.getClass().getCanonicalName());
	}

	public Mono<String>    fallback(Throwable ex) {
		  
		return Mono.just("Hello from fallback");
	}

	public Mono<String>  defaultFallback() {
		return Mono.just("Hello from defaultFallback");
	}

}
